import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt


# 定义二次函数形式
def quadratic_func(x, a, b, c):
    return a * x ** 2 + b * x + c


# 给定的数据点
xdata = np.array([0.001, 0.002, 0.01, 1, 100])
ydata = np.array([0.4, 0.399, 0.2, 0.0001, 0.00001])

# 初始参数猜测值，需要确保对称轴在x=100右侧
p0 = [1, -2 * 100 * 1, 1]  # 这里的p0是任意选择的，可能需要调整以得到更好的结果

# 使用curve_fit进行曲线拟合
try:
    popt, pcov = curve_fit(quadratic_func, xdata, ydata, p0=p0)
    a, b, c = popt
    print(f"拟合得到的参数: a = {a}, b = {b}, c = {c}")
    print(f"对称轴: x = -b/(2a) = {-b / (2 * a)} (应在x=100右侧)")
except RuntimeError as e:
    print(f"拟合失败: {e}")

# 验证函数是否经过给定点
print(f"在 x=0.001 时, y = {quadratic_func(0.001, *popt)}")
print(f"在 x=100 时, y = {quadratic_func(100, *popt)}")

# plt.plot(xdata, ydata)

nt = np.linspace(1, 150, 100)

# ny = 4e-5 * nt ** 2 - 8e-3 * nt + 0.4+1e-5
# 一个2次函数经过(1,13.6944),(150,1.36944),二次项系数为正,对称轴在x=150右侧,两点和函数下方以及y=0的面积约为1340
# ny = 0.279998*nt**2 - 42.197031*nt + 28.222633
ny =0.000108*nt**2 - 0.324132*nt +47.55924
nt0=150
ny0 =0.000108*nt0**2 - 0.324132*nt0+47.55924
plt.plot(nt, ny)
y = -0.080537*nt + 13.449977
plt.plot(nt, y)
plt.show()

 
